<template>
  <div class="settings-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" :index="indexAdd" type="index" width="120" />
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="hAssign(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                background
                layout="sizes,prev,pager,next"
                :total="total"
                :current-page="page"
                :page-sizes="[2, 4, 6, 8]"
                :page-size="pagesize"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 新增/编辑弹框 -->
    <el-dialog
      :title="isEdit ? '编辑' : '修改'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="$refs.roleForm.resetFields()"
    >
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="showDialog=false">取消</el-button>
          <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      v-if="showDialogAssign"
      title="分配权限"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogAssign"
    >
      <AssignPermission :role-id="roleId" @close="showDialogAssign=false" />
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, delRoles, addRoles, editRoles } from '@/api/setting'
import AssignPermission from './assignPermission.vue'

export default {
  components: { AssignPermission },
  data() {
    return {
      roleId: '',
      isEdit: false,
      showDialog: false,
      showDialogAssign: false,
      list: [],
      total: 0, // 总条数
      page: 1, // 当前页码
      pagesize: 2, // 每页2条
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '描述信息不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.initRoles()
  },
  methods: {
    // 点击了分配权限
    hAssign(id) {
      this.showDialogAssign = true
      this.roleId = id
    },
    // 点击编辑按钮
    hEdit(data) {
      this.isEdit = true
      this.showDialog = true
      // 数据回填
      this.roleForm = { ...data }
    },
    // 点击添加按钮
    hAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    // 修改角色
    async doEdit() {
      try {
        await editRoles(this.roleForm)
        this.$message.success('修改角色成功')
        this.showDialog = false
        await this.initRoles()
      } catch (e) {
        this.$message.error('修改失败')
      }
    },
    // 添加角色
    async doAdd() {
      try {
        await addRoles(this.roleForm)
        this.$message.success('添加角色成功')
        this.showDialog = false
        // 添加完成跳到最后一页
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
        await this.initRoles()
      } catch (e) {
        this.$message.error('添加失败')
      }
    },
    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (!valid) return
        // 判断添加还是修改
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    indexAdd(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 删除角色
    async doDel(id) {
      try {
        await delRoles(id)
        this.$message.success('删除成功')
        // 修改页码
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        await this.initRoles()
      } catch (e) {
        this.$message.error('删除失败')
      }
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => { })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.page = 1
      this.initRoles()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      // 重发请求
      this.initRoles()
    },
    async initRoles() {
      // 获取角色列表
      const { data: res } = await getRoles({ page: this.page, pagesize: this.pagesize })
      console.log(res)
      this.list = res.rows
      this.total = res.total
    }
  }
}
</script>
